package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import model.command.Command;
import model.command.CommandPos;
import model.command.SetCommand;
import static utils.RandomAccessFileUtil.readByIndex;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileRotatorUtil {

    private static final String RW_MODE = "rw";

    private static final String TEMP_ROOT = "D:"+File.separator;


    public static void performRotate(RandomAccessFile raf,String filePath) throws IOException {
        // 关闭当前文件
        raf.close();
        // 压缩旧文件
        File currentFile = new File(filePath);
        zipFile(filePath, currentFile);
    }

    private static void zipFile(String filePath, File file) throws FileNotFoundException {
        Path tempPath = null;

        try {

            // 重命名 data.table 为 data2.table
            String newFilePath = filePath.replace(".table", "2.table");
            File renamedFile = new File(newFilePath);
            if (!renamedFile.exists()){
                renamedFile.createNewFile();
            }

            Files.copy(file.toPath(), renamedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            RandomAccessFile oldFile = new RandomAccessFile(filePath, RW_MODE);
            long length = oldFile.length();
            long start = 0;

            // 创建临时文件
            Path path = Paths.get(TEMP_ROOT);
            Path tempDir = path.resolve("tmp_files");
            String tempFileName = "temp_" + System.nanoTime() + ".table";
            tempPath = tempDir.resolve(tempFileName);
            Files.createFile(tempPath);
            File tempFile = tempPath.toFile();
            tempFile.deleteOnExit();
            String tempFilePath = tempFile.toString();
            RandomAccessFile tempRaf = new RandomAccessFile(tempFile, RW_MODE);

            // 确保临时目录存在
            if (!Files.exists(tempDir)) {
                Files.createDirectories(tempDir);
            }

            oldFile.seek(start);
            while (start < length) {
                int cmdLen = oldFile.readInt();
                byte[] bytes = new byte[cmdLen];
                oldFile.read(bytes);
                JSONObject value = JSON.parseObject(new String(bytes, StandardCharsets.UTF_8));
                Command command = CommandUtil.jsonToCommand(value);
                start += 4;
                if (command != null) {
                    if (command instanceof SetCommand){
                        byte[] commandBytes = JSONObject.toJSONBytes(command);

                        RandomAccessFileUtil.writeIntDirectly(tempFilePath, commandBytes.length);
                        int pos = RandomAccessFileUtil.write(tempFilePath, commandBytes);
                    }
                }
                start += cmdLen;
            }
            oldFile.seek(file.length());

            oldFile.close();
            tempRaf.close();

            Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);

            if(Files.deleteIfExists(tempPath) ){
                System.out.println("删除成功");
            }else {
                System.out.println("删除失败 ");
            }

        }catch (IOException e){
                e.printStackTrace();
            }
    }
}
